/*
Copyright 2023, The University of Texas at Austin
All rights reserved.

THIS FILE IS PART OF THE DRAM FAULT ERROR SIMULATION FRAMEWORK

Redistribution and use in source and binary forms, with or without
modification, are permitted provided that the following conditions are
met:


1. Redistributions of source code must retain the above copyright
notice, this list of conditions and the following disclaimer.


2. Redistributions in binary form must reproduce the above copyright
notice, this list of conditions and the following disclaimer in the
documentation and/or other materials provided with the distribution.


3. Neither the name of the copyright holder nor the names of its
contributors may be used to endorse or promote products derived from
this software without specific prior written permission.


THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
"AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS
FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE
COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT,
INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING,
BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN
ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
POSSIBILITY OF SUCH DAMAGE.
*/

/**
 * @file: hsiao.cc
 * @author: Jungrae Kim <dale40@gmail.com>
 * CODEC implementation (HSIAO)
 */

#include <limits.h>
#include <stdlib.h>
#include <string.h>

#include "hsiao.hh"

//--------------------------------------------------------------------
//// From "A Class of Optimal Minimum Odd-weight-column SEC-DED Codes" / Hsiao /
/// 1970
#if 1
//// (72,64) code
//// 8C1 (=8) + 8C3 (=56) + 8C5 (=8 e.a.)
//// total weight = 8 + 3*56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0, 0, 0, 1, 0, 0, 1, 0,
    0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 1, 1, 0, 0, 0, 1, 1, 1,
    0, 0, 1, 1, 1, 0, 0, 0, 0, 0, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 1, 0, 0, 1, 1,
    0, 0, 1, 0, 0, 1, 0, 0, 1, 0, 1, 0, 0, 1, 0, 0, 1, 1, 0, 0, 1, 0, 0, 0, 0,
    0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 1, 1, 0, 0, 0, 1, 1, 1, 0, 0, 1,
    1, 1, 0, 0, 0, 0, 0, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 1, 0, 0, 1, 1, 0, 0, 0,
    1, 0, 0, 1, 1, 0, 0, 1, 0, 0, 1, 0, 0, 1, 1, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0,
    1, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 1, 1, 0, 0, 0, 1, 1, 1, 0, 0, 1, 1, 1, 0,
    0, 0, 0, 0, 1, 1, 1, 1, 1, 1, 1, 1};
#else
// (137,128) code
// 9C1 (=9) + 9C3 (=84) + 9C5 (=44 e.a)
// total weight = 9 + 3*84 + 5*44 = 481
// average number of 1s in each row = 53.4444
// XOR gate levels (per syndrom) = ceil(log2 53.4) = 6
uint8_t HSIAO_PT[] =
    {
        1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1,
        1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
        0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
        0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 1, 1, 1, 1, 1, 0, 0,
        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, 0, 0, 1, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 1, 0, 0, 0, 1, 0, 0, 1, 0,
        0, 1, 1, 0, 0, 0, 0, 1, 0, 0, 0, 0, 1, 0, 0, 0, 1, 0, 0, 1, 0, 0, 1, 1,
        0, 0, 0, 1, 0, 0, 0, 1, 0, 0, 1, 0, 0, 1, 1, 0, 0, 1, 0, 0, 1, 0, 0, 1,
        1, 0, 1, 0, 0, 1, 1, 0, 1, 1, 0, 1, 0, 0, 1, 1, 1, 1, 1, 0, 0, 0, 1, 1,
        1, 1, 0, 1, 0, 0, 0, 1, 1, 1, 0, 1, 1, 0, 0, 0, 1, 1, 0, 1, 1, 1, 0, 0,
        0, 1, 0, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0,
        1, 0, 0, 0, 1, 0, 0, 1, 0, 1, 0, 1, 0, 0, 0, 0, 1, 0, 0, 0, 0, 1, 0, 0,
        0, 1, 0, 0, 1, 0, 1, 0, 1, 0, 0, 0, 1, 0, 0, 0, 1, 0, 0, 1, 0, 1, 0, 1,
        0, 0, 1, 0, 0, 1, 0, 1, 0, 1, 0, 1, 0, 1, 0, 1, 1, 0, 1, 1, 0, 0, 0, 1,
        1, 1, 1, 1, 0, 0, 0, 1, 1, 1, 1, 0, 1, 0, 0, 0, 1, 1, 1, 0, 1, 1, 0, 0,
        0, 1, 1, 0, 1, 1, 1, 0, 0, 0, 1, 0, 1, 1, 1, 1};  //,
//                      0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 1, 0,
//                      0, 0, 1, 0, 0, 1, 0, 1, 1, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0,
//                      1, 0, 0, 0, 1, 0, 0, 1, 0, 1, 1, 0, 0, 0, 0, 1, 0, 0, 0,
//                      1, 0, 0, 1, 0, 1, 1, 0, 0, 0, 1, 0, 0, 1, 0, 1, 1, 0, 0,
//                      1, 0, 1, 1, 0, 1, 1, 1, 0, 0, 0, 0, 1, 1, 1, 1, 1, 0, 0,
//                      0, 1, 1, 1, 1, 0, 1, 0, 0, 0, 1, 1, 1, 0, 1, 1, 0, 0, 0,
//                      1, 1, 0, 1, 1, 1, 0, 0, 0, 1, 0, 1, 1, 1};
// 0,             5,            10,             5,            20,             5,
// 30,             5,            40,             5,            50,
// 5,            60,             5,            70,             5,            80,
// 5,            90,             5,             0,             5,            10,
// 5,            20,             5
#endif

Hsiao::Hsiao(const char *name, int _bitN, int _bitR)
    : BinaryLinearCodec(name, _bitN, _bitR) {
  // G matrix calculation from P matrix (tranposed)
  // G (kxn) = (Ik | P)
  //           MSB   LSB
  for (int i = 0; i < bitK; i++) {
    // map Parity (tranposed) matrix
    for (int j = 0; j < bitR; j++) {
      gMatrix[i * bitN + j] = HSIAO_PT[j * bitK + i];
    }
    // map indentity matrix, Ik
    for (int j = bitR; j < bitN; j++) {
      gMatrix[i * bitN + j] = ((i == (j - bitR)) ? 1 : 0);
    }
  }

  // H matrix calculation from P matrix (tranposed)
  // H (rxn) = (Pt | I(n-k))
  //           MSB      LSB
  for (int i = 0; i < bitR; i++) {
    // map indentity matrix, I(n-k)
    for (int j = 0; j < bitR; j++) {
      hMatrix[i * bitN + j] = ((i == j) ? 1 : 0);
    }
    // map Parity (tranposed) matrix
    for (int j = bitR; j < bitN; j++) {
      hMatrix[i * bitN + j] = HSIAO_PT[i * bitK + (j - bitR)];
    }
  }

  // print(stdout);
  verifyMatrix();
}

ErrorType Hsiao::decode(ECCWord *msg, ECCWord *decoded,
                        std::set<int> *correctedPos) {
  // step 1: copy the message data
  decoded->clone(msg);

  // step 2: generate syndrome
  bool synError = genSyndrome(msg);

  // Step 3: if all of syndrom bits are zero, the word can be assumed to be
  // error free
  if (synError) {
    // Step 4: trying to find a perfect match between syndrom and a column of
    // the matrix

    for (int i = bitN - 1; i >= 0; i--) {
      bool all_equal = true;
      for (int j = bitR - 1; j >= 0; j--) {
        if (syndrom[j] != hMatrix[j * bitN + i]) {  //
          all_equal = false;
          break;
        }
      }
      if (all_equal) {
        // Step 4.1: Syndrome is the same as the i-th column of matrix ->
        // inverth i-th bit
        decoded->invBit(i);
        if (correctedPos != NULL) {
          correctedPos->insert(i);
        }
        if (decoded->isZero()) {
          return CE;
        } else {
          return SDC;
        }
      }
    }

    // step 5: Detected
    return DUE;
  } else {
    return SDC;
  }
}

void Hsiao::verifyMatrix() {
  int max_row_weight = 0;
  int min_row_weight = INT_MAX;
  for (int i = 0; i < bitR; i++) {
    int row_weight = 0;
    for (int j = 0; j < bitN; j++) {
      row_weight += hMatrix[i * bitN + j];
    }
    if (row_weight > max_row_weight) max_row_weight = row_weight;
    if (row_weight < min_row_weight) min_row_weight = row_weight;
  }

  if ((max_row_weight - min_row_weight) > 1) {
    fprintf(stderr,
            "Invalid Hsiao matrix: Max row weight: %d Min row weight: %d\n",
            max_row_weight, min_row_weight);
    exit(-1);
  }

  // G x Ht = 0
  for (int i = 0; i < bitK; i++) {
    for (int j = 0; j < bitR; j++) {
      int temp = 0;
      for (int k = 0; k < bitN; k++) {
        temp ^= gMatrix[i * bitN + k] & hMatrix[j * bitN + k];
      }
      if (temp != 0) {
        fprintf(stderr, "BAD H and G matrix %d\n", i);
        exit(-1);
      }
    }
  }
}

bool Hsiao::genSyn(ECCWord *msg) { return genSyndrome(msg); }
